﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace GodReply.ORM
{
    public class InstanceFactory
    {
        static Assembly assembly = Assembly.Load("GodReply.ORM");
        static Dictionary<string, Type> typeCache = new Dictionary<string, Type>();

        private static string GetClassName(string type, string name)
        {
            return "GodReply.ORM." + type + name;
        }
        private static T CreateInstance<T>(string className)
        {
            Type type;
            if (typeCache.ContainsKey(className))
            {
                type = typeCache[className];
            }
            else
            {
                lock (typeCache)
                {
                    type = assembly.GetType(className);
                    //Check.ArgumentNullException(type, string.Format(ErrorMessage.ObjNotExist, className));
                    if (!typeCache.ContainsKey(className))
                    {
                        typeCache.Add(className, type);
                    }
                }
            }
            var result = (T)Activator.CreateInstance(type, true);
            return result;
        }

        public static IAdo GetAdo(ConnectionConfig currentConnectionConfig)
        {
            IAdo result = CreateInstance<IAdo>(GetClassName(currentConnectionConfig.DbType.ToString(), "Provider"));
            return result;
        }
    }
}
